package utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import android.widget.RemoteViews;

import androidx.core.content.FileProvider;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Date;
import java.util.List;

public class AppUtil {
    public static JSONArray getAppList(Context ctx) {
        List<ResolveInfo> ps;
        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ps = ctx.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL);
        } else {
            ps = ctx.getPackageManager().queryIntentActivities(intent, 0);
        }
        JSONArray appList = new JSONArray();
        for(int i=0;i<ps.size();i++) {
            ResolveInfo pa = ps.get(i);
            String name = pa.loadLabel(ctx.getPackageManager()).toString();
            String packageName = pa.activityInfo.packageName;
            Drawable icon = pa.loadIcon(ctx.getPackageManager());
            icon.setBounds(0, 0, 96,96);
            try {
                PackageInfo pi = ctx.getPackageManager().getPackageInfo(packageName, 0);
                int uid = pi.applicationInfo.uid;
                Integer versionCode = pi.versionCode;
                String versionName = pi.versionName;
                Long dtInstall = pi.firstInstallTime;
                Long dtUpdate = pi.lastUpdateTime;
//                if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                    JSONObject app = new JSONObject();
                    app.put("uid",uid);
                    app.put("name",name);
                    app.put("packageName",packageName);
                    JSONObject to = MyUtil.getTrafficTotal(ctx, uid);
//                    MyUtil.showLog("appList traffic="+name,to);
                    app.put("traffic",to);
                    ImgUtil iu = new ImgUtil();
//                    app.put("icon",iu.getImgStr(iu.drawable2Bitmap(icon)));
                    app.put("versionCode",versionCode);
                    app.put("versionName",versionName);
                    app.put("dtInstall",MyUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", dtInstall));
                    app.put("dtUpdate",MyUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", dtUpdate));
                    long total = to.getLong("mRx")+to.getLong("mTx")+to.getLong("wRx")+to.getLong("wTx");
                    if (total > 1) {
                        appList.put(app);
                    }
//                } else {
//                    //系统应用
//                }
            } catch (PackageManager.NameNotFoundException | JSONException e) {
                e.printStackTrace();
            }
        }
        return appList;
    }
    public static String getAppStatus(Context ctx, String packageNameNet, int versionCodeNet) {
        String result = "";
        List<ResolveInfo> ps;
        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ps = ctx.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL);
        } else {
            ps = ctx.getPackageManager().queryIntentActivities(intent, 0);
        }
        for(int i=0;i<ps.size();i++) {
            ResolveInfo pa = ps.get(i);
            String packageName = pa.activityInfo.packageName;
            if (packageNameNet.equals(packageName)) {
                try {
                    PackageInfo pi = ctx.getPackageManager().getPackageInfo(packageName, 0);
                    Integer versionCode = pi.versionCode;
                    if (versionCodeNet <= versionCode) {
                        result = "installed";
                    } else {
                        result = "update";
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    result = "installed";
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    // 安装apk
    public static boolean installApk(Context ctx,String apkPath) {
        File apkfile = new File(apkPath);
        if (!apkfile.exists()) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Intent install = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + ctx.getPackageName()));
        install.setAction(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addCategory(Intent.CATEGORY_DEFAULT);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                String file_provider = "com.qb.devapps.fileprovider";
                Uri contentUri = FileProvider.getUriForFile(ctx.getApplicationContext(), file_provider, apkfile);
                intent.setAction(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        try {
            ctx.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
